const Datastore = require('nedb')
const path = require('path')
const os = require('os')

const dbPath = path.join(os.homedir(), '.ssh-server', 'ssh-server.db')

const db = new Datastore({
    filename: dbPath,
    autoload: true
})

class Cache {
    _table
    constructor(table) {
        this._table = table
    }
    insert(model) {
        model._table = this._table
        return new Promise((resolve, reject) => {
            db.insert(model, (error, document) => {
                if (error) {
                    return reject(error)
                }
                resolve(document)
            })
        })
    }

    remove(query) {
        query ||= {}
        query._table = this._table
        return new Promise((resolve, reject) => {
            db.remove(query, (error, count) => {
                if (error) {
                    return reject(error)
                }
                resolve(count > 0)
            })
        })
    }

    upsert(query, document) {
        query ||= {}
        query._table = this._table
        document._table = this._table
        return new Promise((resolve, reject) => {
            db.update(
                query,
                document,
                {
                    upsert: true
                },
                (error, count) => {
                    if (error) {
                        return reject(error)
                    }
                    resolve(count > 0)
                }
            )
        })
    }

    findOne(query) {
        query ||= {}
        query._table = this._table
        return new Promise((resolve, reject) => {
            db.findOne(query, (error, document) => {
                if (error) {
                    return reject(error)
                }
                resolve(document)
            })
        })
    }

    find(query) {
        query ||= {}
        query._table = this._table
        return new Promise((resolve, reject) => {
            db.find(query, (error, documents) => {
                if (error) {
                    return reject(error)
                }
                resolve(documents)
            })
        })
    }
}

module.exports = Cache
